#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

mode_t mode = 0666;

class NamePipe
{
public:
    NamePipe(const std::string &name = "fifo")
        : _name(name)
    {
    }

    void Creat()
    {
        int n = mkfifo(_name.c_str(), mode);
        if (n < 0)
        {
            exit(1);
        }
    }

    void OpenForWrite()
    {
        _fd = open(_name.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            std::cout << "打开管道失败" << std::endl;
            exit(1);
        }
    }

    void OpenForRead()
    {
        _fd = open(_name.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            std::cout << "打开管道失败" << std::endl;
            exit(1);
        }
    }

    int Read()
    {
        char buffer[1024] = {0};
        ssize_t n = read(_fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
        else if (n == 0)
        {
            std::cout << "对端关闭" << std::endl;
        }
        else if (n < 0)
        {
            std::cout << "读取失败" << std::endl;
        }
        return n;
    }

    void Write()
    {
        std::string str;
        std::getline(std::cin, str);
        write(_fd, str.c_str(), str.size());
    }

    void Close()
    {
        close(_fd);
    }

    void Remove()
    {
        unlink(_name.c_str());
    }

    ~NamePipe()
    {
    }

private:
    int _fd = -1;
    std::string _name;
};